package com.mapapp.flutter_mapapp.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mapapp.flutter_mapapp.MainActivity;
import com.mapapp.flutter_mapapp.R;
import com.mapapp.flutter_mapapp.adapter.SearchResultAdapter;
import com.mapapp.flutter_mapapp.application.MyApplication;
import com.mapapp.flutter_mapapp.bean.MapDetailBean;
import com.mapapp.flutter_mapapp.bean.MapResult;
import com.mapapp.flutter_mapapp.persenter.SearchPersenter;
import com.mapapp.flutter_mapapp.util.MyActivityManager;
import com.mapapp.flutter_mapapp.view.SearchViewInterface;
import com.mapapp.flutter_mapapp.widget.flowlayout.FlowLayout;
import com.mapapp.flutter_mapapp.widget.flowlayout.TagAdapter;
import com.mapapp.flutter_mapapp.widget.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SearchActivity extends ImmersiveBaseActivity implements View.OnClickListener , SearchViewInterface{
    private static final String TAG = "SearchActivity";

    @BindView(R.id.ll_map_bottom)
    LinearLayout llMapBottom;
    @BindView(R.id.ll_search_bottom)
    LinearLayout llSearchBottom;
    @BindView(R.id.ll_mine_bottom)
    LinearLayout llMineBottom;
    @BindView(R.id.iv_map_bottom)
    ImageView ivMapBottom;
    @BindView(R.id.iv_search_bottom)
    ImageView ivSearchBottom;
    @BindView(R.id.iv_mine_bottom)
    ImageView ivMineBottom;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.tv_search_cancel)
    TextView tvSearchCancel;
    @BindView(R.id.iv_search_clear_history)
    ImageView ivSearchClearHistory;
    @BindView(R.id.tf_search_history)
    TagFlowLayout tfSearchHistory;
    @BindView(R.id.rv_search_result)
    RecyclerView rvSearchResult;
    @BindView(R.id.ll_search_history)
    LinearLayout llSearchHistory;

    private List<String> recordList = new ArrayList<>();
    private TagAdapter mRecordsAdapter;
    private SearchPersenter mPersenter;
    private List<MapDetailBean> mResults = new ArrayList<>();
    private List<MapDetailBean> mAllAddress = new ArrayList<>();
    private List<MapDetailBean> caseAddress = new ArrayList<>();
    private ArrayList<String> addresses = new ArrayList<>();;
    private SearchResultAdapter mAdapter;
    private List<String> mAddresses = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);

        mContext = this;
        initview();
        mPersenter = new SearchPersenter(this,this,lifecycleSubject);
        mPersenter.getAllAddress();
    }

    private void initview() {
        setListener();
        ivSearchBottom.setImageResource(R.mipmap.icon_barclick_serch);
        initHistoryView();
        initList();
    }

    private void setListener() {
        llMineBottom.setOnClickListener(this);
        llMapBottom.setOnClickListener(this);
        ivSearch.setOnClickListener(this);
        tvSearchCancel.setOnClickListener(this);
        ivSearchClearHistory.setOnClickListener(this);
        etSearch.addTextChangedListener(watcher);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.ll_map_bottom:
                intent = new Intent(mContext, MainActivity.class);
                startActivity(intent);
                MyActivityManager.getActivityManager().pop(this);
                break;
            case R.id.ll_mine_bottom:
                intent = new Intent(mContext, MineActivity.class);
                startActivity(intent);
                MyActivityManager.getActivityManager().pop(this);
                break;
            case R.id.iv_search:
                String searchinfo = etSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(searchinfo)) {
//                    recordList.add(0,searchinfo);
//                    mRecordsAdapter.setData(recordList);
//                    mRecordsAdapter.notifyDataChanged();
                    mPersenter.saveSearch(searchinfo);
                    mPersenter.searchByaddress(searchinfo);
                }
                hideKeyboard();
                break;
            case R.id.tv_search_cancel:
                llSearchHistory.setVisibility(View.VISIBLE);
                rvSearchResult.setVisibility(View.GONE);
                etSearch.setText("");
                hideKeyboard();
                break;
            case R.id.iv_search_clear_history:
                recordList.clear();
                mRecordsAdapter.setData(recordList);
                mRecordsAdapter.notifyDataChanged();
                mPersenter.deleteSearchHistory();
                break;
        }
    }

    private void initList(){
        LinearLayoutManager llmanage = new LinearLayoutManager(this);
        rvSearchResult.setLayoutManager(llmanage);
        mAdapter = new SearchResultAdapter(mAddresses,this);
        rvSearchResult.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new SearchResultAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                MapDetailBean result = mResults.get(position);
                MyApplication.mSearchResult = result;
                Intent intent = new Intent(mContext,MainActivity.class);
                mContext.startActivity(intent);
                MyActivityManager.getActivityManager().pop(SearchActivity.this);
            }
        });
    }

    private void initHistoryView() {
        //历史记录点击事件
        tfSearchHistory.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public void onTagClick(View view, int position, FlowLayout parent) {
                etSearch.setText(recordList.get(position));
                mPersenter.searchByaddress(recordList.get(position));
            }
        });
        //创建历史标签适配器
        //为标签设置对应的内容
        mRecordsAdapter = new TagAdapter<String>(recordList) {

            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(mContext).inflate(R.layout.tv_history,
                        tfSearchHistory, false);
                //为标签设置对应的内容
                tv.setText(s);
                return tv;
            }
        };
        tfSearchHistory.setAdapter(mRecordsAdapter);
    }

    @Override
    public void initHistoryData(ArrayList<String> list) {
        recordList.clear();
        recordList.addAll(list);
        mRecordsAdapter.setData(recordList);
        mRecordsAdapter.notifyDataChanged();
    }

    @Override
    public void showSearchResult(List<MapDetailBean> data){
        llSearchHistory.setVisibility(View.GONE);
        rvSearchResult.setVisibility(View.VISIBLE);
        if(data.size() == 0){
            Toast.makeText(mContext,"未查询到可用数据！",Toast.LENGTH_SHORT).show();
        }
        mResults = data;
        mAddresses.clear();
        for(int i = 0 ; i < mResults.size() ; i ++){
            mAddresses.add(mResults.get(i).getAddress());
        }
        mAdapter = new SearchResultAdapter(mAddresses,this);
        mAdapter.setOnItemClickListener(new SearchResultAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                MapDetailBean result = mResults.get(position);
                MyApplication.mSearchResult = result;
                Intent intent = new Intent(mContext,MainActivity.class);
                mContext.startActivity(intent);
                MyActivityManager.getActivityManager().pop(SearchActivity.this);
            }
        });
        rvSearchResult.setAdapter(mAdapter);
        mAdapter.notify(mAddresses);
    }

    @Override
    public void setAlladdress(List<MapDetailBean> data) {
        mAllAddress = data;
        if(mAllAddress != null){
            for(int i = 0 ; i < mAllAddress.size() ; i ++){
                addresses.add(mAllAddress.get(i).getRegionName());
            }
        }
    }

    private void hideKeyboard(){
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(etSearch.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            manageAddress();
        }
    };

    private void manageAddress(){
        String searchinfo = etSearch.getText().toString().trim();
        if(!"".equals(searchinfo)){
            ArrayList<String> caseaddresname = new ArrayList<>();;
            caseAddress.clear();
            for(int i = 0 ; i < addresses.size() ; i ++){
                if(addresses.get(i).contains(searchinfo)){
                    caseAddress.add(mAllAddress.get(i));
                    caseaddresname.add(mAllAddress.get(i).getRegionName());
                }
            }
            llSearchHistory.setVisibility(View.GONE);
            rvSearchResult.setVisibility(View.VISIBLE);
            SearchResultAdapter adapter = new SearchResultAdapter(caseaddresname,this);
            rvSearchResult.setAdapter(adapter);
            adapter.setOnItemClickListener(new SearchResultAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    MapDetailBean result = caseAddress.get(position);
                    mPersenter.saveSearch(caseAddress.get(position).getRegionName());
                    MyApplication.mSearchResult = result;
                    Intent intent = new Intent(mContext,MainActivity.class);
                    mContext.startActivity(intent);
                    MyActivityManager.getActivityManager().pop(SearchActivity.this);
                }
            });
        }else{
            llSearchHistory.setVisibility(View.VISIBLE);
            rvSearchResult.setVisibility(View.GONE);
        }
    }
}
